<?php

namespace Biz\service;

use Biz\cache\brand\BrandResumeInfo;
use Biz\model\brand\Brand;
use Biz\service\wiki\Wiki;
use Doraemon\cache\UserCounter;
use Doraemon\model\Member as dbUser;
use Doraemon\model\MemberExtendInfo;
use Doraemon\pockets\config\IniConfig;
use Doraemon\service\Follow;
use Doraemon\service\statSign\Basic as statSign;
use Doraemon\service\User;
use Biz\service\brand\Brand as BrandService;
use Doraemon\service\User as sUser;
use Doraemon\service\WikiBasic\Schedule;
use Doraemon\tools\BlockType;
use Doraemon\tools\Curl;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Hhz\AdministrativeRegion\Region;

class BrandPreFecture
{

    const DEFAULT_PAGESIZE = 20;
    const RECOMMEND_PAGESIZE = 8;
    const RECOMMEND_ONOFF_FILE = '/home/adm_rsync_dir/recommend_onoff.json';
    const RECOMMEND_TYPE_HOT = 1;//推荐类型-热门品牌
    const RECOMMEND_TYPE_DAY = 2;//推荐类型-每日推荐

    public static function getRecommendBrands($uid = 0, $sid = 0, $cate_id_str = '0', $length = self::DEFAULT_PAGESIZE, $recommend_type = self::RECOMMEND_TYPE_HOT)
    {
        $rec_info = self::getFromCurl($uid, $sid, $cate_id_str, $length, $recommend_type);
        return $rec_info;
    }

    public static function getFromCurl($uid, $sid, $cate_id_str, $length, $recommend_type = self::RECOMMEND_TYPE_HOT)
    {
        $rec_info = [];
        try {
            $config = IniConfig::getConfigSelect('mod_userprofile', 'brand_prefecture');
            $url = $config['host'] . "?uid=" . $uid . "&sid=" . $sid . "&cate_id_str=" . $cate_id_str . "&rec_length=" . $length;
            if ($recommend_type == self::RECOMMEND_TYPE_DAY) { //判断是否是每日推荐品牌
                $url = $url . '&recommend_type=' . $recommend_type;
            }
            $result = Curl::Request('GET', $url);
            Log::debug("func:getCFrecommend#action:get", $result);
            if ($result['code'] == 1 && is_string($result['data'])) {
                $result = json_decode($result['data'], true);
            }
            if (isset($result['data']['content_list']) && $result['data']['content_list'] && is_array($result['data']['content_list'])) {
                $rec_info = ['list' => (array)$result['data']['content_list'], 'total_num' => $result['data']['total_num']];
            }
        } catch (\Exception $e) {
            Log::warning($e->getMessage());
        }
        return $rec_info;
    }

    /**
     * 好物频道页-精选品牌
     * @param string $module_name
     * @param int $uid
     * @param int $sid
     * @param int $cate_id_str
     * @param int $pagesize
     * @param array $brand_id_arr
     * @param int $recommend_type
     * @return array
     * @throws \Exception
     */
    public static function recommendBrandsForChannelHead($module_name = '', $uid = 0, $sid = 0, $cate_id_str = 0, $pagesize = self::RECOMMEND_PAGESIZE, $brand_id_arr = [], $recommend_type = self::RECOMMEND_TYPE_HOT): array
    {
        $list = [];
        $now = time();
        if ($module_name == '好物主频道精选品牌' && strtotime('2022-06-18') <= $now && $now < strtotime('2022-06-19')) {
            $brand_ids = [3275, 2649, 464, 2235, 338, 2056, 363, 3330, 3322, 275, 318, 313, 2551, 2513, 2725];
            shuffle($brand_ids);
            $brand_ids = array_slice($brand_ids, 0, 8);
        } else {
            $recommend_brands = self::getRecommendBrands($uid, $sid, $cate_id_str, $pagesize, $recommend_type);
            $brand_ids = $recommend_brands ? array_column($recommend_brands['list'], 'obj_id') : [];
        }
        if (!$brand_ids) {
            $brand_ids = Brand::getPackTypePro();
        }
        if ($brand_ids) {
            if ($brand_id_arr) {
                $brand_ids = array_slice(array_unique(array_merge($brand_id_arr, $brand_ids)), 0, 12);
            }
            $hasCounter = ($module_name == '好物主频道精选品牌') ? true : false;
            $hasBrandResumeInfo = ($module_name == '好物主频道精选品牌') ? false : true;
            $brandUserInfos = BrandService::getBrandUserInfos($brand_ids, $hasCounter, $hasBrandResumeInfo);
            $sort = 0;
            foreach ($brandUserInfos as $brandId => $brandUserInfo) {
                $list[] = [
                    "type" => BlockType::TYPE_BRAND_LIST,
                    "brand" => $brandUserInfo,
                    "statSign" => statSign::genStatSign(statSign::MODULE_FINE_GOODS_FINE_GOODS_MAIN_RECOMM_BRANDS, [
                        statSign::EXTEND_KEY_OBJ_ID => $brandId, statSign::EXTEND_KEY_INDEX => $sort], ['module_name' => $module_name])
                ];
                $sort++;
            }
        }
        return $list;
    }

    /**
     * 好物主页算法推荐品牌
     * @param string $module_name
     * @param int $uid
     * @param int $sid
     * @param int $cate_id_str
     * @param int $pagesize
     * @return array
     * @throws \Exception
     */
    public static function recommendBrands($module_name = '', $uid = 0, $sid = 0, $cate_id_str = 0, $pagesize = self::RECOMMEND_PAGESIZE, $brand_id_arr = [], $recommend_type = self::RECOMMEND_TYPE_HOT)
    {
        $brand_list = [];
        $recommend_brands = (array)self::getRecommendBrands($uid, $sid, $cate_id_str, $pagesize, $recommend_type);

        $brand_ids = array_column($recommend_brands['list'], 'obj_id');
        if (in_array(date('Ymd'), ['20201021', '20201025', '20201028'])) {//广告
            $index = (time() % 2) ? 1 : 0;
            $brand_ids[$index] = 827;
            $brand_ids = array_unique($brand_ids);
        }

        $brandIsOrder = false;//是否需要排序 (发现品牌页面-今日推荐品牌需要[前三个必须显示后台配置的品牌])
        if ($brand_id_arr) { //判断是否在后台设置了前置品牌（数量为3个）
            $brandIsOrder = true;
            $brand_ids = array_unique(array_merge($brand_id_arr, $brand_ids));
        }
        $sort = array_flip($brand_ids);
        $uids = Brand::getUidsByIds($brand_ids, $brandIsOrder);
        $user_infos = sUser::getBrandCards($uids);
        $wikis = Schedule::getGroupBrandGoods($brand_ids);
        $resumeInfos = BrandResumeInfo::getResumeInfo($brand_ids);
        $resumeInfos = $resumeInfos[0];
        if ($uids && is_array($uids)) {
            foreach ($uids as $brand_id => $uid) {
                $wikiIds = (isset($wikis[$brand_id]) && $wikis[$brand_id]) ? array_column($wikis[$brand_id], 'id') : [];
                $wiki_list = Wiki::getWikiBaseList($wikiIds);
                $wiki_list = $wiki_list ? array_values($wiki_list) : [];
                if ($wiki_list && is_array($wiki_list)) {
                    $brand_list[$brand_id] = [
                        "type" => BlockType::TYPE_BRAND_LIST,
                        "brand" => [
                            "user_info" => $user_infos[$uid],
                            "counter" => UserCounter::getOne($uid),
                            "wiki_list" => $wiki_list,//todo 是否需要删除
                            'resume_info' => isset($resumeInfos[$brand_id]) ? $resumeInfos[$brand_id] : []
                        ],
                        "statSign" => statSign::genStatSign(statSign::MODULE_FINE_GOODS_FINE_GOODS_MAIN_RECOMM_BRANDS, [
                            statSign::EXTEND_KEY_OBJ_ID => $brand_id, statSign::EXTEND_KEY_INDEX => $sort[$brand_id]], ['module_name' => $module_name])
                    ];
                }
            }
        }
        $list = [];
        foreach ($brand_ids as $brandId) {
            if (isset($brand_list[$brandId])) {
                $list[] = $brand_list[$brandId];
            }
        }
        return $list;
    }

    //好物子频道推荐品牌
    public static function recommendBrandsNotWiki($uid = 0, $relate_id = 0, $cate_ids = 0, $tab_name = '', $module_name = '')
    {
        $list = [];
        $recommend_brands = (array)BrandPreFecture::getRecommendBrands($uid, $relate_id, $cate_ids, self::RECOMMEND_PAGESIZE);
        $brand_ids = array_column($recommend_brands['list'], 'obj_id');
        $sort = array_flip($brand_ids);
        $uids = Brand::getUidsByIds($brand_ids);
        $user_infos = sUser::getBrandCards($uids);
        if ($uids && is_array($uids)) {
            foreach ($uids as $brand_id => $uid) {
                $list[$sort[$brand_id]] = [
                    "type" => BlockType::TYPE_HOT_BRAND_LIST,
                    "brand" => [
                        "user_info" => $user_infos[$uid],
                        "counter" => sUser::get_counter($uid, dbUser::AUTH_USER_BRAND)
                    ],
                    "statSign" => statSign::genStatSign(statSign::MODULE_FINE_GOODS_FINE_GOODS_SON_RECOMM_BRANDS, [
                        statSign::EXTEND_KEY_OBJ_ID => $brand_id, statSign::EXTEND_KEY_INDEX => $sort['brand_id']], ['tab_name' => $tab_name, 'module_name' => $module_name])
                ];
            }
            rsort($list);
        }
        return $list;
    }

    public static function getTempWikiList($brandId)
    {
        $wikiList = [];
        if ($brandId == 2639) {
            $wikiList = [
                [
                    'id' => 0,
                    'basic_id' => 0,
                    'basic_title' => '',
                    'basic_state' => '',
                    'type' => 1,
                    'title' => 'F+极简系列  厨房系统',
                    'ori_min_price' => 5000,
                    "ori_max_price" => 5000,
                    "actual_min_price" => 5000,
                    "actual_max_price" => 5000,
                    "actual_stock" => 1,
                    "activity_stock" => 0,
                    "shop_id" => 0,
                    "category_id" => 0,
                    "second_category_id" => 0,
                    "status" => 0,
                    "wiki_status" => 0,
                    "cover_img" => 'https://img.haohaozhu.cn/Op-imageShow/67e2d30cr0cn0K600qg0i7g?iv=1',
                    "brand_id" => $brandId,
                    'recommendation' => ''
                ],
                [
                    'id' => 0,
                    'basic_id' => 0,
                    'basic_title' => '',
                    'basic_state' => '',
                    'type' => 1,
                    'title' => 'F+极简系列  衣帽间系统',
                    'ori_min_price' => 5000,
                    "ori_max_price" => 5000,
                    "actual_min_price" => 5000,
                    "actual_max_price" => 5000,
                    "actual_stock" => 1,
                    "activity_stock" => 0,
                    "shop_id" => 0,
                    "category_id" => 0,
                    "second_category_id" => 0,
                    "status" => 0,
                    "wiki_status" => 0,
                    "cover_img" => 'https://img.haohaozhu.cn/Op-imageShow/36e0530kc0kb0TB00qg0i9t?iv=1',
                    "brand_id" => $brandId,
                    'recommendation' => ''
                ]
            ];
        }
        return $wikiList;
    }

}